﻿using CzJ_ttsc.Models.Database;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Threading.Tasks;

namespace CzJ_ttsc.Controllers
{
    public class yhController : Controller
    {
        private readonly ttscContext _db;
        public yhController(ttscContext db)
        {
            _db = db;
        }

        [HttpPost("login")]
        public async Task<IActionResult> Login([FromBody] LoginModel loginModel)
        {
            if (loginModel == null || string.IsNullOrEmpty(loginModel.UserName) || string.IsNullOrEmpty(loginModel.Password))
            {
                return BadRequest("Username and password are required.");
            }

            var user = await _db.Users
                .FirstOrDefaultAsync(u => u.UserName == loginModel.UserName && u.Password == loginModel.Password);

            if (user == null)
            {
                return Unauthorized("Invalid username or password.");
            }

            // Generate a token (for simplicity, return a static token, consider using JWT in a real application)
            var token = "static-token"; // Replace with actual token generation logic

            return Ok(new { Token = token, UserName = user.UserName, Email = user.Email });
        }
        [HttpPost("register")]
        public async Task<IActionResult> Register([FromBody] RegisterModel registerModel)
        {
            if (registerModel == null || string.IsNullOrEmpty(registerModel.UserName) || string.IsNullOrEmpty(registerModel.Password) || string.IsNullOrEmpty(registerModel.Email))
            {
                return BadRequest("All fields are required.");
            }

            var existingUser = await _db.Users.FirstOrDefaultAsync(u => u.UserName == registerModel.UserName || u.Email == registerModel.Email);
            if (existingUser != null)
            {
                return Conflict("User with the same username or email already exists.");
            }

            var user = new User
            {
                UserName = registerModel.UserName,
                Password = registerModel.Password,
                Email = registerModel.Email,
                CreateTime = DateTime.UtcNow
            };

            _db.Users.Add(user);
            await _db.SaveChangesAsync();

            return Ok("User registered successfully.");
        }
    }
    public class LoginModel
    {
        public string UserName { get; set; }
        public string Password { get; set; }
    }
    public class RegisterModel
    {
        public string UserName { get; set; }
        public string Password { get; set; }
        public string Email { get; set; }
    }
}

